<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width,initial-scale=1.0,maximum-scale=1.0,minimum-scale=1.0,user-scalable=no">
    <title>电池监测模拟</title>
    <script src="https://www.jq22.com/jquery/jquery-2.1.1.js"></script>
    <div>
        起始值：<input type="text" name="value" id="initVal">
        <br/>
        <br/>
        每3秒递减值：<input type="text" name="value" id="step">
        <br/>
        <br/>
        <div>当前值 ： <span id="nowVal"></span></div>
        <br/>
        <br/>
        <button onclick="StartPolling($('#initVal').val())">开始</button>
        <button onclick="StopPolling()">停止</button>
    </div>
</body>
<script type="text/javascript">
    var flag = true;
    function StopPolling(){
        flag = false;
    }

    function StartPolling(initVal){
        console.log(flag);
        if (!flag) {
            return;
        }

        if (initVal <= 0) {
            return;
        }
        $('#nowVal').html(initVal);
        setTimeout("setSimulation()", 3000);
    }

    // setTimeout("changeState()",3000 );
    function setSimulation() {
        var val = $('#nowVal').html() - $('#step').val()
        $('#nowVal').html(val);
        val = parseFloat(val);
        if (isNaN(val)) {
            alert('请填写正确的数值');
            return;
        }
        let url = "{{ URL::asset('setBatterySimulation') }}";
        let data = {
            _token: '{{ csrf_token() }}',
            val: val
        }
        $.ajax({
            type : "POST",
            url : url,
            data : data,
            success : function(result) {
                if (result.code == 1) {
                    StartPolling(val);
                } else {
                    alert('fail')
                }
            },
            //请求失败，包含具体的错误信息
            error : function(e){
                layer.close(e);
                console.log(e.status);
                console.log(e.responseText);
            }
        });
    }
</script>
</html>